package net.lab1024.sa.admin.module.business.yuqing.service;

import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import jakarta.annotation.Resource;
import lombok.extern.slf4j.Slf4j;
import net.lab1024.sa.admin.module.business.yuqing.constant.SentimentEnum;
import net.lab1024.sa.admin.module.business.yuqing.constant.YuqingConst;
import net.lab1024.sa.admin.module.business.yuqing.dao.NewsArticleDao;
import net.lab1024.sa.admin.module.business.yuqing.domain.entity.NewsArticleEntity;
import net.lab1024.sa.admin.module.business.yuqing.domain.form.NewsArticleQueryForm;
import net.lab1024.sa.admin.module.business.yuqing.domain.vo.NewsArticleExcelVO;
import net.lab1024.sa.admin.module.business.yuqing.domain.vo.NewsArticleVO;
import net.lab1024.sa.admin.module.business.yuqing.util.NewsImportUtil;
import net.lab1024.sa.base.common.domain.PageResult;
import net.lab1024.sa.base.common.domain.ResponseDTO;
import net.lab1024.sa.base.common.util.SmartBeanUtil;
import net.lab1024.sa.base.common.util.SmartPageUtil;
import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;

/**
 * 舆情文章 Service
 *
 * @Author 1024创新实验室: 卓大
 * @Date 2025-01-15 10:00:00
 * @Wechat zhuda1024
 * @Email lab1024@163.com
 * @Copyright  <a href="https://1024lab.net">1024创新实验室</a>
 */
@Slf4j
@Service
public class NewsArticleService {

    @Resource
    private NewsArticleDao newsArticleDao;

    /**
     * 分页查询舆情文章
     */
    public ResponseDTO<PageResult<NewsArticleVO>> queryPage(NewsArticleQueryForm queryForm) {
        Page page = SmartPageUtil.convert2PageQuery(queryForm);
        List<NewsArticleVO> list = newsArticleDao.queryPage(page, queryForm);
        
        // 处理内容显示长度和情感倾向描述
        list.forEach(vo -> {
            // 截取内容长度
            if (StringUtils.isNotBlank(vo.getContent()) && vo.getContent().length() > YuqingConst.MAX_CONTENT_DISPLAY_LENGTH) {
                vo.setContent(vo.getContent().substring(0, YuqingConst.MAX_CONTENT_DISPLAY_LENGTH) + "...");
            }
            
            // 设置情感倾向描述
            vo.setSentimentDesc(getSentimentDesc(vo.getSentiment()));
        });
        
        PageResult<NewsArticleVO> pageResult = SmartPageUtil.convert2PageResult(page, list);
        return ResponseDTO.ok(pageResult);
    }

    /**
     * 获取文章详情
     */
    public ResponseDTO<NewsArticleVO> getDetail(Long articleId) {
        NewsArticleEntity entity = newsArticleDao.selectById(articleId);
        if (entity == null || entity.getDeletedFlag()) {
            return ResponseDTO.userErrorParam("文章不存在");
        }
        
        // 更新查看次数
        newsArticleDao.updateViewCount(articleId);
        
        NewsArticleVO vo = SmartBeanUtil.copy(entity, NewsArticleVO.class);
        vo.setSentimentDesc(getSentimentDesc(vo.getSentiment()));
        
        return ResponseDTO.ok(vo);
    }

    /**
     * 删除文章
     */
    @Transactional(rollbackFor = Exception.class)
    public ResponseDTO<String> delete(Long articleId) {
        NewsArticleEntity entity = newsArticleDao.selectById(articleId);
        if (entity == null || entity.getDeletedFlag()) {
            return ResponseDTO.userErrorParam("文章不存在");
        }
        
        entity.setDeletedFlag(true);
        newsArticleDao.updateById(entity);
        
        return ResponseDTO.ok();
    }

    /**
     * 批量删除文章
     */
    @Transactional(rollbackFor = Exception.class)
    public ResponseDTO<String> batchDelete(List<Long> articleIds) {
        if (articleIds == null || articleIds.isEmpty()) {
            return ResponseDTO.userErrorParam("请选择要删除的文章");
        }
        
        newsArticleDao.batchDelete(articleIds);
        return ResponseDTO.ok();
    }

    /**
     * 导出文章数据
     */
    public List<NewsArticleExcelVO> exportData(NewsArticleQueryForm queryForm) {
        List<NewsArticleVO> list = newsArticleDao.queryAll(queryForm);
        
        List<NewsArticleExcelVO> excelList = SmartBeanUtil.copyList(list, NewsArticleExcelVO.class);
        excelList.forEach(excel -> {
            excel.setSentimentDesc(getSentimentDesc(list.get(excelList.indexOf(excel)).getSentiment()));
        });
        
        return excelList;
    }

    /**
     * 导入新闻数据
     */
    @Resource
    private NewsImportUtil newsImportUtil;

    public ResponseDTO<String> importNewsData() {
        try {
            String filePath = "_file/news_list.xls";
            String result = newsImportUtil.importNewsFromCsv(filePath);
            return ResponseDTO.ok(result);
        } catch (Exception e) {
            log.error("导入新闻数据失败", e);
            return ResponseDTO.userErrorParam("导入失败：" + e.getMessage());
        }
    }

    /**
     * 获取情感倾向描述
     */
    private String getSentimentDesc(String sentiment) {
        if (StringUtils.isBlank(sentiment)) {
            return SentimentEnum.NEUTRAL.getDesc();
        }
        
        for (SentimentEnum sentimentEnum : SentimentEnum.values()) {
            if (sentimentEnum.getValue().equals(sentiment)) {
                return sentimentEnum.getDesc();
            }
        }
        
        return SentimentEnum.NEUTRAL.getDesc();
    }
} 